const Information = require("../model/information");

module.exports = {
  // 获取资料列表
  information_list: async (req, res) => {
    const { page, limit } = req.query;
    const offset = (page - 1) * limit;
    try {
      const informationList = await Information.findAndCountAll({
        offset,
        limit,
        order: [["create_time", "DESC"]],
      });
      res.json({ code: 1, message: "获取资料列表成功", data: informationList });
    } catch (err) {
      console.error(err);
      res.status(500).json({ code: 500, message: "服务器错误" });
    }
  },
  // 添加资料
  information_add: async (req, res) => {
    const { file_name, file_size, file_url } = req.body;
    try {
      // 先查询资料是否存在
      if (await Information.findOne({ where: { file_name } })) {
        return res.json({ code: -1, message: "资料名称已存在" });
      }
      const information = await Information.create({ file_name, file_size, file_url });
      if (!information) {
        return res.json({ code: -1, message: "添加资料失败" });
      }
      res.json({ code: 1, message: "添加资料成功" });
    } catch (err) {
      console.error(err);
      res.status(500).json({ code: 500, message: "服务器错误" });
    }
  },
  // 修改资料
  information_update: async (req, res) => {
    const { file_id, file_name } = req.body;
    try {
      // 先查询资料是否存在
      const informationRecord = await Information.findByPk(file_id);
      if (!informationRecord) {
        return res.json({ code: -1, message: "资料不存在" });
      }
      if (informationRecord.file_name === file_name) {
        return res.json({ code: 1, message: "修改资料成功" });
      }
      if (await Information.findOne({ where: { file_name } })) {
        return res.json({ code: -1, message: "资料名称已存在" });
      }
      const information = await Information.update({ file_name }, { where: { file_id } });
      if (!information) {
        return res.json({ code: -1, message: "修改资料失败" });
      }
      res.json({ code: 1, message: "修改资料成功" });
    } catch (err) {
      console.error(err);
      res.status(500).json({ code: 500, message: "服务器错误" });
    }
  },
  // 删除资料
  information_delete: async (req, res) => {
    const { file_id } = req.query;
    try {
      // 先查询资料是否存在
      const informationRecord = await Information.findByPk(file_id);
      if (!informationRecord) {
        return res.json({ code: -1, message: "资料不存在" });
      }
      const information = await Information.destroy({ where: { file_id } });
      if (!information) {
        return res.json({ code: -1, message: "删除资料失败" });
      }
      res.json({ code: 1, message: "删除资料成功" });
    } catch (err) {
      console.error(err);
      res.status(500).json({ code: 500, message: "服务器错误" });
    }
  },
};
